<?php
abstract class TagsAbstract {
	protected $templateFile = ''; //模板文件名
	protected $attr = array (); //属性
	protected $value = ''; //如果是嵌套格式，则为内部数据
	protected $tmplCacheFile = ''; //缓存文件路径
	protected $sign = '';
	
	public function replaceTag($attr, $value = '', $tagInfo) {
		//dump($value);
		$this->init ( $attr,$value );
		$widgetDao = model ( 'Widget' );
		
		//$checkCache = $widgetDao->checkCache ( $this->sign );
		//if (! $checkCache) {
			//静态数据
		//	$content = $widgetDao->getCache ( $this->sign );
		//} else {
			//动态数据，需要重新渲染
			if(!empty($value)){
				//从包围的内容获取样式
				ob_start ();
				ob_implicit_flush ( 0 );
				$var = $this->replace ( $checkCache );
				extract ( $var, EXTR_OVERWRITE );
				include $this->bulidCache ($value);
				$content = ob_get_clean ();
			}else{
				//从数据库以及模板文件内获取样式
					ob_start ();
					ob_implicit_flush ( 0 );
					$var = $this->replace ( $checkCache );
					extract ( $var, EXTR_OVERWRITE );
					include $this->bulidCache ();
					$content = ob_get_clean ();
			}
		//	if($this->attr['cacheTime'] != 0){
		//		$widgetDao->saveCache ( $this->sign, $content );
		//	}
		//}
		return $content;
	}
	
	public function parseTag($attr, $value = '', $tagInfo) {
		//dump($value);
		$this->init ( $attr,$value );
		$widgetDao = model ( 'Widget' );
		//dump($this->sign);
		$hasWidget = $widgetDao->checkHasWidget ( $this->sign );
		//dump($this->sign);
		if ($hasWidget) {
			return $this->sign;
		}
		$map ['pluginId'] = $this->sign;
		$map ['tagLib'] = $tagInfo ['tagLib'];
		$map ['pageId'] = empty ( $attr ['pageId'] ) ? 0 : $attr ['pageId'];
		$map ['channelId'] = empty ( $attr ['channelId'] ) ? 0 : $attr ['channelId'];
		$map ['content'] = $value;
		$ext ['templatePath'] = $this->getTemplateFile ();
		$ext ['attr'] = serialize ( $attr );
		$ext ['tagInfo'] ['name'] = $tagInfo ['tagInfo'] ['name'];
		$map ['cacheTime'] = isset($attr['cacheTime'])?intval($attr['cacheTime']):0;
		$ext ['tagInfo'] ['path'] = $tagInfo ['tagInfo'] ['path'];
		$map ['ext'] = serialize ( $ext );
		$map ['cTime'] = time ();
		$map ['mTime'] = time ();
		$result =  model ( 'Widget' )->add ( $map );
		
		return $this->sign;
	}
	
	protected function bulidCache($template = "") {
		// 编译得到php的缓存编译程序
		if(isset($this->tmplCacheFile) && is_file($this->tmplCacheFile)) return $this->tmplCacheFile;
		$tpl = Think::instance ( 'ThinkTemplate' );
		if(!is_file($this->templateFile) && empty($template)){
			$template = model('Widget')->getTemplateByPluginId($this->sign);
		}
		if(empty($template)){
			$tmplContent = $tpl->loadPHPTemplate ( $this->templateFile );
		}else{
			$tmplContent = $tpl->compiler($template);
		}
		$tmplContent = $this->replaceContent($tmplContent);
		//将缓存编译程序写入缓存文件
		// 检测分组目录
		if (! is_dir ( C ( 'CACHE_PATH' ) ))
			mk_dir ( C ( 'CACHE_PATH' ) );
			//重写Cache文件
		if (false === file_put_contents ( $this->tmplCacheFile, trim ( $tmplContent ) ))
			throw_exception ( L ( '_CACHE_WRITE_ERROR_' ) );
		return $this->tmplCacheFile;
	}
	
	protected function init($attr, $value = '') {
		$this->attr = $attr;
		$this->templateFile = $this->getTemplateFile ();
		
		if (! empty ( $value )){
			$this->value = $value;
			$this->sign = md5 ( json_encode($this->attr). $this->value );
		}else{
			$this->sign = md5 ( json_encode($this->attr). $this->templateFile );
		}
		if(is_array($this->attr['head_link']) && !empty($this->attr['head_link'])){
			foreach($this->attr['head_link'] as &$value){
				$value->url = str_replace('[@]','&',$value->url);
			}
		}
		$this->tmplCacheFile = C ( 'CACHE_PATH' ) . $this->sign . C ( 'TMPL_CACHFILE_SUFFIX' );

	}
	
	protected function replaceContent($content){
		    // 系统默认的特殊变量替换
        $replace =  array(
            '../Public'		=>	APP_PUBLIC_PATH,// 项目公共目录
            '__PUBLIC__'	=>	WEB_PUBLIC_PATH,// 站点公共目录
            '__TMPL__'		=>	APP_TMPL_PATH,  // 项目模板目录
            '__ROOT__'		=>	__ROOT__,       // 当前网站地址
            '__APP__'		=>	__APP__,        // 当前项目地址
            '__URL__'		=>	__URL__,        // 当前模块地址
            '__ACTION__'	=>	__ACTION__,     // 当前操作地址
            '__SELF__'		=>	__SELF__,       // 当前页面地址
			'__THEME__'		=>	__THEME__,		// 主题页面地址
			'__UPLOAD__'	=>	__UPLOAD__,		// 上传文件地址
        );
        if(C('TOKEN_ON')) {
            if(strpos($content,'{__TOKEN__}')) {
                // 指定表单令牌隐藏域位置
                $replace['{__TOKEN__}'] =  $this->buildFormToken();
            }elseif(strpos($content,'{__NOTOKEN__}')){
                // 标记为不需要令牌验证
                $replace['{__NOTOKEN__}'] =  '';
            }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) {
                // 智能生成表单令牌隐藏域
                $replace[$match[0]] = $this->buildFormToken().$match[0];
            }
        }
        // 允许用户自定义模板的字符串替换
        if(is_array(C('TMPL_PARSE_STRING')) )
            $replace =  array_merge($replace,C('TMPL_PARSE_STRING'));
        $content = str_replace(array_keys($replace),array_values($replace),$content);
        return $content;
	}
	
	/**
	 * 解析
	 */
	abstract function getTemplateFile($tpl = '');
	
	
	/**
	 * 替换
	 */
	abstract function replace($checkCache);
}
?>